package dao.impl;

import bean.RecordBean;
import bean.UserBean;
import dao.IRecordDAO;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class RecordDAOImpl extends BaseDAO implements IRecordDAO {
    @Override
    public void insert(int id, String describe, Double money, LocalDate date) {
        this.setConnection();
        String sql = "insert into t_record(r_describe,r_money,u_r_id,r_date) values(?,?,?,?)";
            try {
                ps = con.prepareStatement(sql);
                ps.setObject(1, describe);
                ps.setObject(2, money);
                ps.setObject(3, id);
                ps.setObject(4, date);
                ps.executeUpdate();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                this.closeConnection();
            }
    }
    @Override
    public List<RecordBean> getRecordsByUserId(int userId) {
        this.setConnection();
        String sql = "SELECT * FROM t_record LEFT JOIN t_user ON u_id=u_r_id WHERE u_r_id=?";
        List<RecordBean> list = new ArrayList<>();
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, userId);
            rs = ps.executeQuery();
            while (rs.next()) {
                RecordBean recordBean = new RecordBean();
                recordBean.setId(rs.getInt("pk_id"));
                recordBean.setDescription(rs.getString("r_describe"));
                recordBean.setDate(LocalDate.parse(rs.getString("r_date")));
                recordBean.setBalance(rs.getInt("r_money"));
                UserBean userBean = new UserBean();
                userBean.setId(rs.getInt("u_r_id"));
                recordBean.setUser(userBean);
                list.add(recordBean);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }
}
